package com.cl.ks.controller;

import com.cl.ks.entity.BaseEntity;
import com.cl.ks.service.BaseService;
import com.cl.ks.utils.CommonResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.List;

public class BaseController<Entity extends BaseEntity> {
    private final BaseService<Entity> service;

    public BaseController(BaseService<Entity> service) {
        this.service = service;
    }

    @PostMapping("findOne")
    @ApiOperation("条件查询一条数据")
    public CommonResult findByEntity(@RequestBody Entity entity){
        return CommonResult.success(service.findByEntity(entity));
    }
    @PostMapping("page")
    @ApiOperation("分页查询")
    public CommonResult page(@RequestBody Entity entity,@RequestHeader(name = "Authorization", defaultValue = "") String auth) {
        Page<Entity> page = service.page(entity, auth);
        return CommonResult.success(page);
    }

    @PostMapping("listBy")
    @ApiOperation("分页查询")
    public CommonResult listBy(@RequestBody Entity entity,@RequestHeader(name = "Authorization", defaultValue = "") String auth) {
        return CommonResult.success(service.listBy(entity,auth));
    }
    @GetMapping("list")
    @ApiOperation("查询所有")
    public CommonResult list() {
        return CommonResult.success(service.list());
    }

    @PostMapping("saveAll")
    @ApiOperation("批量新增/修改")
    public CommonResult saveAll(@RequestBody List<Entity> entities,@RequestHeader(name = "Authorization", defaultValue = "") String auth) {
        return CommonResult.success(service.saveAll(entities,auth));
    }

    @PostMapping("save")
    @ApiOperation("新增/修改")
    public CommonResult save(@RequestBody Entity entity, @RequestHeader(name = "Authorization", defaultValue = "") String auth) {
        try {
            return CommonResult.success(service.save(entity,auth));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @GetMapping("deleteById")
    @ApiOperation("通过id删除")
    public CommonResult deleteById(Integer id) {
        service.deleteById(id);
        return CommonResult.success("","成功");
    }

    @PostMapping("delete")
    @ApiOperation("通过对象属性删除")
    public CommonResult delete(Entity entity) {
        service.delete(entity);
        return CommonResult.success("","成功");
    }

}

